package com.act;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.LoginInfo;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.control.UserControl;
import com.xike.kyt.R;
import com.mUI.MyProgressDialog;
import com.xike.util.MLog;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class LoginAct extends BaseAct implements OnClickListener {

	private EditText edt_phonuNum, edt_pwd;
	private Button btn_login;
	private TextView tv_register, tv_findpwd;
	private ImageButton img_close;
	BaseBean requestResult;
	String strUserName;
	boolean isNewLogin = false;

	public static LoginAct instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login);

		instance = this;

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey("userName")) {
				strUserName = bundle.getString("userName");
			}
			if (bundle.containsKey("isNewLogin")) {
				isNewLogin = bundle.getBoolean("isNewLogin");
			}
		}

		initViews();
		UserControl.logout();
	}

	@Override
	protected void initViews() {
		img_close = (ImageButton) findViewById(R.id.login_imgBtn_close);

		edt_phonuNum = (EditText) findViewById(R.id.login_edt_phoneNum);
		edt_pwd = (EditText) findViewById(R.id.login_edt_password);
		tv_findpwd = (TextView) findViewById(R.id.login_tv_findpwd);
		tv_register = (TextView) findViewById(R.id.login_tv_register);

		btn_login = (Button) findViewById(R.id.login_btn_login);

		img_close.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		tv_findpwd.setOnClickListener(this);
		tv_register.setOnClickListener(this);

		if (StringUtil.isNotNull(strUserName)) {
			edt_phonuNum.setText(strUserName);
			edt_pwd.setFocusable(true);
			edt_pwd.setFocusableInTouchMode(true);
			edt_pwd.requestFocus();
		}
	}

	@Override
	protected void updateViews() {
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.login_btn_login) {
			if (checkInput()) {
				serviceGetMd5key();
			}
		} else if (v.getId() == R.id.login_imgBtn_close) {
			finish();
		} else if (v.getId() == R.id.login_tv_findpwd) {
			Intent it_findPwd = new Intent(this, FindPasswordAct.class);
			it_findPwd.putExtra("phoneNum", "");
			startActivity(it_findPwd);
		} else if (v.getId() == R.id.login_tv_register) {
			Intent it_register = new Intent(this, RegisterAct.class);
			startActivity(it_register);
		}
	}

	private boolean checkInput() {
		String strPhoneNum = MyUtil.getEditTextContent(edt_phonuNum);
		if (!StringUtil.isNotNull(strPhoneNum)) {
			mToast.showToast(this, "请输入手机号");
			return false;
		}

		if (!MyUtil.isPhoneNumberValid(strPhoneNum)) {
			mToast.showToast(this, "请输入有效的手机号");
			return false;
		}

		String strPwd = MyUtil.getEditTextContent(edt_pwd);
		if (!StringUtil.isNotNull(strPwd)) {
			mToast.showToast(this, "请输入登录密码");
			return false;
		}
		return true;
	}

	private void serviceGetMd5key() {

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("signature", StringUtil.MD5(Constant.APPSERRET)));
		params.add(new BasicNameValuePair("user_name", MyUtil.getEditTextContent(edt_phonuNum)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_MD5KEY, params);

		// // 本地缓存
		// if (LocalFileHelper.fileIsExited(strUrl)) {
		// BaseBean result = gson.fromJson(LocalFileHelper.getContentFromFile("url"), BaseBean.class);
		// dealRequestResult(result);
		// return;
		// }
		// 网络请求
		MyProgressDialog.show(this, true);
		client.get(this, strUrl, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				MLog.e("serviceGetMd5key", "result:" + responseString);
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null) {
					if (!result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
						mToast.showToast(LoginAct.this, result.getError_description());
					} else {
						try {
							String strMd5Key = new JSONObject(responseString).getString("md5_key");
							serviceLogin(strMd5Key);
							return;
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				} else {
					mToast.showToast(LoginAct.this, getString(R.string.net_error));
				}
				MyProgressDialog.cancle();

			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				MyProgressDialog.cancle();
				mToast.showToast(LoginAct.this, getString(R.string.net_error));
			}
		});

	}

	private void serviceLogin(String strMd5key) {

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("signature", StringUtil.MD5(Constant.APPSERRET + StringUtil.MD5(MyUtil.getEditTextContent(edt_pwd) + strMd5key))));
		params.add(new BasicNameValuePair("user_name", MyUtil.getEditTextContent(edt_phonuNum)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_LOGIN, params);

		client.get(this, strUrl, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				LoginInfo result = gson.fromJson(responseString, LoginInfo.class);
				MLog.e("serviceLogin", "result:" + responseString);
				dealRequestResult(result);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				MyProgressDialog.cancle();
				mToast.showToast(LoginAct.this, getString(R.string.net_error));
			}
		});
	}

	private void dealRequestResult(LoginInfo result) {
		MyProgressDialog.cancle();
		if (result != null) {
			if (!result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				mToast.showToast(LoginAct.this, result.getError_description());
			} else {
				// 登录成功
				UserControl.saveLoginInfo(result);
//				UserControl.setUserInfoChanged(true);
				if (isNewLogin) {
					startActivity(new Intent(LoginAct.this, MainAct.class));
				} else {
					setResult(1);
				}
				finish();
			}
		} else {
			mToast.showToast(LoginAct.this, getString(R.string.net_error));
		}
	}

}
